<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/10 0010
 * Time: 22:36
 */
include './socket_server.php';

class job
{
    protected $worker_num = 3;
    protected $manager_num = 2;
    protected $msg_key;
    protected $msg_queue;
    protected $master_pid;

    public function __construct()
    {
        $this->master_pid = getmypid();
        $this->monitor();//进程的回收

    }

    public function run()
    {
        $this->msg_key = ftok(__DIR__, 'q'); //注意在php创建消息队列，第二个参数会直接转成字符串，可能会导致通讯失败
        $this->msg_queue = msg_get_queue($this->msg_key);
        //manager 进程组
        for ($i = 0; $i < $this->manager_num; $i++) {
            $this->create_manager();
        }
        //worker进程组
        for ($i = 0; $i < $this->worker_num; $i++) {
            $this->create_worker();
        }

    }

    public function create_worker()
    {
        $process = new Swoole\Process(function (Swoole\Process $process) {
//            sleep(10);
            while (true) {
                //从消息队列当中去读取数据
                msg_receive($this->msg_queue, 0, $message_type, 1024, $message, false);
                //业务逻辑
                sleep(2);
//                echo 'worker进程接收处理数据' . posix_getpid() . ':' . $message . PHP_EOL;
            }
        });

        $process->start();
    }

    public function create_manager()
    {
        $process = new Swoole\Process(function (Swoole\Process $process) {
//            sleep(10);
            $server = new socket_server('tcp://0.0.0.0:9500');
            $server->onMessage = function ($fd, $message) {
                msg_send($this->msg_queue, 1, $message, false, false);
            };
            $server->listen();
        });

        $process->start();
    }

    //进程监听
    public function monitor()
    {
        echo '进程回收';
        while ($res = Swoole\Process::wait(false)) {

//            var_dump($res);
        }
        swoole_timer_tick(10, function () {
            $stat = msg_stat_queue($this->msg_queue);
//            var_dump($stat);
            //超过50个开启一个子进程
            if ($stat['msg_qnum'] > 10) {
                var_dump('是否执行');
                //$this->create_worker();
                //直接创建有问题swoole禁止了，发送信号触发信号创建,
                //可以使用swoole的信号监听机制
                swoole_process::kill($this->master_pid, SIGRTMAX - 4);
            }
        });
    }
}

$job = new job();
$job->run();